package stephencarmody.fonttexture;

import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.io.File;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.swing.JFrame;

public final class FontTexture {
    
    // GUI Components
    private static JFrame frame;
    private static ToolBar toolbar;
    private static Texture texture;
    
    /** Updates the texture when a new family or style is provided */
    public static void update(String family, int style) {
        frame.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        texture.setFont(family, style);
        frame.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
    }
    
    /**
     * Saves the current texture to the specified file.
     *  
     * @throws IOException
     */
    public static void save(File f) throws IOException {
    	texture.save(f);
    }
    
    /**
     * Create the GUI and show it.  For thread safety,
     * this method should be invoked from the
     * event-dispatching thread.
     */
    private static void createAndShowGUI() {
        toolbar = new ToolBar();
        frame = new JFrame("Font Texture");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setIconImage(new ImageIcon(toolbar.getClass().getResource("icons/fonttexture.png")).getImage());
        frame.addComponentListener( new ComponentAdapter() {
        		public void componentResized(ComponentEvent e)
        		{
        			int size = Math.max(frame.getWidth(), frame.getHeight());
        			size = texture.setSize(size);
        			frame.pack();
        		}
        	});
        frame.add(toolbar, BorderLayout.NORTH);
        texture = new Texture(256);
        frame.add(texture, BorderLayout.CENTER);
        frame.pack();
        toolbar.actionPerformed(null);
        frame.setVisible(true);
    }

    /** Application entrypoint. */
    public static void main(String[] args) {
        // Schedule a job for the event-dispatching thread
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                createAndShowGUI();
            }
        });
    }
    
}